package com.qujia.station.utils;

import com.google.gson.Gson;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.utils.StringUtils;
import com.qujia.station.domain.Oil;
import com.qujia.station.domain.PayOrder;
import com.qujia.station.domain.StationDeviceManage;
import com.qujia.station.enums.PrintEnum;
import com.qujia.station.service.IOilService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class YiLianYunPrinterUtil {

    static RedisCache redisCache;


    @Autowired
    public void setRedisCache(RedisCache redisCache){
        YiLianYunPrinterUtil.redisCache =  redisCache;

    }


    static IOilService staticOilService;

    @Resource
    private IOilService oilService;

    @PostConstruct
    public void init(){
        this.staticOilService = oilService;
    }


    public static AjaxResult print(String content, StationDeviceManage stationDevice, PayOrder payOrder){
        HashMap<String, String> audioMap = new HashMap<>();
        if(!"2".equals(payOrder.getUtmSource()) && StringUtils.isNotEmpty(payOrder.getCustomerPhone())){
            audioMap.put("手机尾号", Objects.isNull(payOrder.getCustomerPhone()) ? "" : payOrder.getCustomerPhone().substring(7,11));
        }
        audioMap.put("加油金额", payOrder.getReceivableAmt().toString() + "元");
        audioMap.put("支付金额", payOrder.getAmt().toString() + "元");
        audioMap.put("枪号", payOrder.getOilGun());
        if (StringUtils.isNotBlank(payOrder.getOilName())) {
            Oil oil =  staticOilService.selectOilById(Long.valueOf(payOrder.getOilName()));
            if (oil != null) {
                audioMap.put("油品", oil.getOilName().replace("#","号"));
            }else{
                audioMap.put("油品", "");
            }
        }else{
            audioMap.put("油品", "");
        }



        String audio = stationDevice.getAudio();

        StringBuffer sb = new StringBuffer();
        String deviceFactory = stationDevice.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
        switch (printEnum){
            case YILIANYUN:
        try {
            String[] split = audio.split(";");

            //加油语音
            String oilOrderAudio = split[0];
            List<String> oilOrderAudioList = Arrays.asList(oilOrderAudio.split(","));
            sb.append("<audio>");
            boolean hasPhone = org.apache.commons.lang3.StringUtils.isNotBlank(payOrder.getCustomerPhone());
            for (String audioContent : oilOrderAudioList) {
                //繁星订单不需要播报手机号
                if("手机尾号".equals(audioContent) && ("2".equals(payOrder.getUtmSource()) || !hasPhone)){
                    continue;
                }
                sb.append(audioContent + audioMap.get(audioContent));
            }
            sb.append("</audio>");
            log.info("播报语音：{}",sb);



            }catch (Exception e){
            sb = new StringBuffer("<audio>手机尾号").append(payOrder.getCustomerPhone().substring(7, 11)).append("支付金额").append(payOrder.getAmt().stripTrailingZeros().toPlainString())
                    .append("元").append("加油金额").append(payOrder.getReceivableAmt().stripTrailingZeros().toPlainString()).append("元").append(payOrder.getOilGun()).append("号油枪").append(payOrder.getOilName()).append("号油,</audio>");
        }
                String ylyContent = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>","").replace("<BOLD><B>","");
                StringBuffer finalContent = sb.append(ylyContent);


                //初始化控制器类
                Methods m= Methods.getInstance();
                Object token = redisCache.getCacheObject("STATION:DEVICE:" + stationDevice.getClientId());
                Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
                if(Objects.nonNull(token)){
                    String print = m.print(stationDevice.getClientId(),stationDevice.getDeviceNo(), finalContent.toString(), random6.toString(), token.toString());
                    log.info("小票机返回值{}",print);
                    org.json.JSONObject json = new org.json.JSONObject(print);
                    if("0".equals(json.getString("error"))){
                        return AjaxResult.success("补打小票成功");
                    }
                }
                //初始化终端信息
                m.init(stationDevice.getClientId(), stationDevice.getClientSecret());
                //获取token
                String refreshToken = m.getFreedomToken();
                //存入redis
                redisCache.setCacheObject("STATION:DEVICE:" + stationDevice.getClientId(),refreshToken,30, TimeUnit.DAYS);

                String print = m.print(stationDevice.getDeviceNo(), finalContent.toString(), random6.toString());
                log.info("小票机返回值2{}",print);
                org.json.JSONObject json = new org.json.JSONObject(print);
                if("0".equals(json.getString("error"))){
                    return AjaxResult.success("补打小票成功");
                }

            case YILIANYUNK4:
                StringBuffer sbVoice = new StringBuffer();
                sbVoice.append("<VN>2</VN>").append("<VD>").append(payOrder.getReceivableAmt().stripTrailingZeros().toPlainString()).append("</VD>").append("<VN>0</VN>")
                        .append("<VN>4</VN>").append("<VD>").append(payOrder.getOilGun()).append("</VD>")
                        .append("<VN>5</VN>").append("<VD>").append(payOrder.getOilName()).append("</VD>");
                String ylyContentK4 = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>","").replace("<BOLD><B>","");
                StringBuffer finalContentK4 = sbVoice.append(ylyContentK4);

                Methods mK4= Methods.getInstance();
                Object tokenK4 = redisCache.getCacheObject("STATION:DEVICE:" + stationDevice.getClientId());
                Integer random6K4 = (int) ((Math.random() * 9 + 1) * 100000);
                if(Objects.nonNull(tokenK4)){
                    String printK4 = mK4.print(stationDevice.getClientId(),stationDevice.getDeviceNo(), finalContentK4.toString(), random6K4.toString(), tokenK4.toString());
                    log.info("小票机返回值{}",printK4);
                    org.json.JSONObject jsonK4 = new org.json.JSONObject(printK4);
                    if("0".equals(jsonK4.getString("error"))){
                        return AjaxResult.success("补打小票成功");
                    }
                }
                //初始化终端信息
                mK4.init(stationDevice.getClientId(), stationDevice.getClientSecret());
                //获取token
                String refreshTokenK4 = mK4.getFreedomToken();
                //存入redis
                redisCache.setCacheObject("STATION:DEVICE:" + stationDevice.getClientId(),refreshTokenK4,30, TimeUnit.DAYS);

                String printK4 = mK4.print(stationDevice.getDeviceNo(), finalContentK4.toString(), random6K4.toString());
                log.info("小票机返回值2{}",printK4);
                org.json.JSONObject jsonK4 = new org.json.JSONObject(printK4);
                if("0".equals(jsonK4.getString("error"))){
                    return AjaxResult.success("补打小票成功");
                }

        }


        return AjaxResult.error("补打小票失败");
    }

    public static void main(String[] args) {
        //设置内置语音
        Methods m= Methods.getInstance();
        m.init("1057002640","56ff1c6596b740c2faf66e741642063f");
        String refreshToken = m.getFreedomToken();
        m.refreshToken();

        ArrayList<Object> content = new ArrayList<>();
        content.add("号枪加油收款成功");
        content.add(9);
        content.add(0);

        Gson gson = new Gson();
        String s = gson.toJson(content);
//        String oil = m.setVoice("4004833516", s, 0);
//        m.refreshToken();
        String oilGun = m.setVoice("4004833516", s, 1,m.refreshToken());
//        m.refreshToken();
//        String amount = m.setVoice("4004833516", "元", 2);
        String audio = "<VD>92</VD><VN>1</VN>";
        String content1 = audio + "测试内容111";
        Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
        String print = m.print("4004833516", content1, random6.toString());
        String printStatus = m.getPrintStatus("4004833516");
        System.out.println(printStatus);
    }


}
